//********************************树控件自带函数开始********************************************//
var setting = {
    view: {
        selectedMulti: false
    },
    edit: {
        enable: true,
        showRemoveBtn: false,
        showRenameBtn: false
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        beforeDrag: beforeDrag,
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        onClick: zTreeOnClick,
        onRemove: onRemove
    }
};
var zNodes ="";
var dataBaseSelNodes = "";

var log, className = "dark";
function beforeDrag(treeId, treeNodes) {
    return false;
}
function beforeRemove(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name) ;
    return confirm("确认删除 -- " + treeNode.name + " 吗？");
}

//删除节点
function onRemove(e, treeId, treeNode) {
    showLog("[ " + getTime() + " onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
}
function beforeRename(treeId, treeNode, newName) {
    if (newName.length == 0) {
        alert("名称不能为空.");
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function () {
            zTree.editName(treeNode)
        }, 10);
        return false;
    }else
    {
        $.ajax({
            async : true,
            type: "get",
            url: "/EtlXml/UpdateNodeName",
            data:{
                nodeid:treeNode.id,
                nodename:newName
            },
            beforeSend: function (XMLHttpRequest) {
                //ShowLoading();
            },
            success: function (data) {
                if (data != 0) {
                    //var dataval = eval('(' + data+ ')')
                    //return dataval;
                }
                else
                {
                    //alert("加载节点信息失败!");
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                //HideLoading();
            },
            error: function () {
                //请求出错处理
            }
        });
    }
    return true;
}
function showLog(str) {
    if (!log) log = $("#log");
    log.append("<li class='" + className + "'>" + str + "</li>");
    if (log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}
function getTime() {
    var now = new Date(),
        h = now.getHours(),
        m = now.getMinutes(),
        s = now.getSeconds(),
        ms = now.getMilliseconds();
    return (h + ":" + m + ":" + s + " " + ms);
}

function AddNowEditView(mynodetype) {

}



var newLayerCount = 1;
var newCreateJobCount = 1;
var newUpdateJobCount = 1;
var newValCount = 1;
var newConnectionCount = 1;
var newQueryCount = 1;
var newScriptCount = 1;

var nowCount = 1;

function add(e) {
    //获取当前选择的类型
    var nowSelectType = $("#seleAddNode").val();

    //UpdateNodeNumber();

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        isParent = false,
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    var nowName;
    var nowNodeType;
    var xmlId;
    var nowJobId="";
    var pid = treeNode.id;
    var nodeid;
    var iconstr;

    if(treeNode.isParent == true){
        nodeid = (treeNode.id * 10) +(treeNode.children.length+1);
    }else {
        nodeid = (treeNode.id * 10) + 1;
    }

    switch (nowSelectType) {
        case 'layer':
            nowName = "层级" +  (GetPidNodeTypeNum(pid,'layer') + 1);
            nowNodeType = "layer";
            nowJobId=0;
            xmlId = "layer"+newLayerCount;
            iconstr = "/res/css/zTreeStyle/img/diy/layer.png";
            newLayerCount++;
            break;
        case 'createjob':
            ;
            nowName = "新建任务" +(GetPidNodeTypeNum(pid,'createjob') + 1);
            nowNodeType = "createjob";
            nowJobId = nodeid;
            xmlId = "createjob";
            iconstr = "/res/css/zTreeStyle/img/diy/job.png";
            newCreateJobCount++;
            break;
        case 'updatejob':
            nowName = "更新任务" +(GetPidNodeTypeNum(pid,'updatejob') + 1);
            nowNodeType = "updatejob";
            nowJobId = nodeid;
            xmlId = "updatejob";
            iconstr = "/res/css/zTreeStyle/img/diy/update.png";
            newUpdateJobCount++;
            break;
        case 'properties':
            nowName = "properties" + (GetPidNodeTypeNum(pid,'properties') + 1);
            nowNodeType = "properties";
            nowJobId = treeNode.jobid;             //preprity与connection的jobid就等于上级节点的iD,因为上级就是任务节点
            xmlId = "properties";
            iconstr = "/res/css/zTreeStyle/img/diy/properties.png";
            newValCount++;
            $("#divValView").show();
            $("#divConnView").hide();
            $("#divQueryView").hide();
            $("#divScriptView").hide();
            break;
        case 'connection':
            nowName = "connection" + (GetPidNodeTypeNum(pid,'connection') + 1);
            nowNodeType = "connection";
            nowJobId = treeNode.jobid;
            xmlId = "connection";
            iconstr = "/res/css/zTreeStyle/img/diy/connection.png";
            newConnectionCount++;
            $("#divValView").hide();
            $("#divConnView").show();
            $("#divQueryView").hide();
            $("#divScriptView").hide();
            break;
        case 'query':
            nowName = "query" + (GetPidNodeTypeNum(pid,'query') + 1);
            nowNodeType = "query";
            nowJobId = treeNode.jobid;
            xmlId = "query";
            iconstr = "/res/css/zTreeStyle/img/diy/query.png";
            newQueryCount++;
            $("#divValView").hide();
            $("#divConnView").hide();
            $("#divQueryView").show();
            $("#divScriptView").hide();
            break;
        case 'script':
            nowName = "script" + (GetPidNodeTypeNum(pid,'script') + 1);
            nowNodeType = "script";
            nowJobId = treeNode.jobid;
            xmlId = "script";
            iconstr = "/res/css/zTreeStyle/img/diy/script.png";
            newScriptCount++;
            $("#divValView").hide();
            $("#divConnView").hide();
            $("#divQueryView").hide();
            $("#divScriptView").show();
            break;
        default:
            return;
            break;
    }


    if (treeNode) {
        treeNode = zTree.addNodes(treeNode, {
            id: nodeid,
            pId: treeNode.id,
            isParent: isParent,
            name: nowName,
            mytreetype: nowSelectType,
            icon:iconstr,
            jobid:nowJobId
        });
    } else {
        treeNode = zTree.addNodes(null, {
            id: ((treeNode.id * 10) + treeNode.children.length),
            pId: 0,
            isParent: isParent,
            name: nowName,
            mytreetype: nowSelectType,
            icon:iconstr,
            jobid:nowJobId
        });
    }
    if (treeNode) {
        zTree.editName(treeNode[0]);
    } else {
        alert("叶子节点被锁定，无法增加子节点");
    }

    //调整节点位置

    var AjaxParma = nodeid+"|"+pid+"|"+nowName+"|"+nowSelectType+"|"+nowJobId;

    //新增完节点后，向表中添加此节点
    AddNodeAjax(AjaxParma);

    //移动节点
    TreeMoveNode(pid,nodeid);

    $("#hidID").val(nodeid);
    $("#hidPID").val(pid);
    $("#hidName").val(nowName);
    $("#hidTreeType").val(nowNodeType);

    $("#seleAddNode").empty();
    $("#seleAddNode").prepend("<option value='0'>---请选择---</option>");
};

function edit() {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    if (nodes.length == 0) {
        alert("请先选择一个节点");
        return;
    }
    zTree.editName(treeNode);
}
;
function remove(e) {

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    if (nodes.length == 0) {
        alert("请先选择一个节点");
        return;
    }
    if(confirm("确认删除 -- " + treeNode.name + " 吗？")){
        //前台删除
        var callbackFlag = $("#callbackTrigger").attr("checked");
        zTree.removeNode(treeNode, callbackFlag);
        //删除数据库中节点，根据ID和PID
        $.ajax({
            async : true,
            type: "get",
            url: "/EtlXml/DeleNode",
            data:{
                nodeid:treeNode.id
            },
            beforeSend: function (XMLHttpRequest) {
                //ShowLoading();
            },
            success: function (data) {
                if (data != 0) {
                    //var dataval = eval('(' + data+ ')')
                    //return dataval;
                }
                else
                {
                    //alert("加载节点信息失败!");
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                //HideLoading();
            },
            error: function () {
                //请求出错处理
            }
        });
    }
}
;
function clearChildren(e) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    if (nodes.length == 0 || !nodes[0].isParent) {
        alert("请先选择一个父节点");
        return;
    }
    zTree.removeChildNodes(treeNode);
}
;
//********************************树控件自带函数结束*************************************************************************************************************************************//

//********************************自定义函数开始******************************************************************************************************************************************//

//节点单击事件
function zTreeOnClick(event, treeId, treeNode) {
    //设置隐藏字段的值
    $("#hidID").val(treeNode.id);
    $("#hidPID").val(treeNode.pId);
    $("#hidName").val(treeNode.name);
    $("#hidTreeType").val(treeNode.mytreetype);
    //加载相应节点信息
    //var nowClickNodeInfo = GetTreeNodeInfoByIDAjax(treeNode.id);


    //显示相应编辑DOM
    if(treeNode.mytreetype == "properties"){
        $("#divValView").show();
        $("#divConnView").hide();
        $("#divQueryView").hide();
        $("#divScriptView").hide();

        $("#btnValSave").show();

        //$("#txtval").val(treeNode.nodecontent);
        editorPre.getSession().setValue(treeNode.nodecontent);
    }else if(treeNode.mytreetype == "connection"){
        GetSelDatabasesAjax();
        $("#selConn").prepend("<option value='0' selected>---请选择---</option>");
        if(treeNode.connectionid != null && treeNode.connectionid !=""){
            //$('#selConn').attr('value',treeNode.connectionid);
            $("#selConn").val(treeNode.connectionid);
        }
        $("#txtmiddleContent").val(treeNode.nodecontent);
        $("#divValView").hide();
        $("#divConnView").show();
        $("#divQueryView").hide();
        $("#divScriptView").hide();

        $("#btnValSave").show();

    }else if(treeNode.mytreetype == "query"){

        GetSelDatabasesAjax();
        $("#selQuery").prepend("<option value='0' selected>---请选择---</option>");
        if(treeNode.connectionid != null && treeNode.connectionid !=""){
            //$('#selConn').attr('value',treeNode.connectionid);
            $("#selQuery").val(treeNode.connectionid);
        }
        //查询节点是否有子节点，有节加载内容

        if(treeNode.children != null && treeNode.children.length > 0){
            editorQuery.getSession().setValue(treeNode.children[0].comment);
        }else{
            editorQuery.getSession().setValue(treeNode.nodecontent);
        }

        $("#divValView").hide();
        $("#divConnView").hide();
        $("#divQueryView").show();
        $("#divScriptView").hide();

        $("#btnValSave").show();

    }else if(treeNode.mytreetype == "script"){
        GetSelDatabasesAjax();
        $("#selScript").prepend("<option value='0' selected>---请选择---</option>");
        if(treeNode.connectionid != null && treeNode.connectionid !=""){
            //$('#selConn').attr('value',treeNode.connectionid);
            $("#selScript").val(treeNode.connectionid);
        }

        //查询节点是否有子节点，有节加载内容
        if(treeNode.children != null && treeNode.children.length > 0){
            editorScript.getSession().setValue(treeNode.children[0].comment);
        }else{
            editorScript.getSession().setValue(treeNode.nodecontent);
        }

        $("#divValView").hide();
        $("#divConnView").hide();
        $("#divQueryView").hide();
        $("#divScriptView").show();

        $("#btnValSave").show();
    }else if(treeNode.mytreetype == "createjob" || treeNode.mytreetype == "updatejob" ){
        //加载ETLXML
        editor.getSession().setValue("");
        //设置隐藏任务ID
        $("#hidJobID").val(treeNode.id);
        $("#hidJobName").val(treeNode.name);
        GetJobEtlXml(treeNode.id);
    }

    //根据节点类型，动态加载下拉框
    var nowNodeType = treeNode.mytreetype;
    zTreeInitSelect(nowNodeType);
};

//加载下拉框
function zTreeInitSelect(nodetype) {
    $("#seleAddNode").empty();
    var layerOption = "<option value='layer'>层级</option>";
    var createjobOption = "<option value='createjob'>新建任务";
    var updatejobOption = "<option value='updatejob'>更新任务</option>";
    var valOption = "<option value='properties'>properties</option>";
    var connectionOption = "<option value='connection'>connection</option>";
    var queryOption = "<option value='query'>query</option>";
    var scriptOption = "<option value='script'>script</option>";

    var optiongs;

    if (nodetype == "RootNode") {
        optiongs = layerOption;
    } else if (nodetype == "layer") {
        optiongs = createjobOption + updatejobOption;
    } else if (nodetype == "createjob" || nodetype == "updatejob") {
        optiongs = valOption + connectionOption + queryOption + scriptOption;
    } else if (nodetype == "properties") {
        optiongs = "";
    } else if (nodetype == "connection") {
        optiongs = "";
    } else if (nodetype == "query") {
        optiongs = queryOption + scriptOption;
    } else if (nodetype == "script") {
        optiongs = scriptOption;
    }

    $("#seleAddNode").append(optiongs);
    $("#seleAddNode").prepend("<option value='0'>---请选择---</option>");
}

//下拉框选中事件
function myTreeSelectChange() {
    //alert(1);
}

//保存
function SaveNodeInfoAjax() {
    var content = "";
    var connectionid = "";
    var nodeid = $("#hidID").val();
    var nodeTreeType = $("#hidTreeType").val();

    //判断类型,获取相应的值
    if(nodeTreeType == "properties"){
        content = editorPre.getSession().getValue();
    }else if(nodeTreeType == "connection"){
        content = $("#selConn").val()+"|"+$("#txtmiddleContent").val();
    }else if(nodeTreeType == "query"){
        connectionid = $("#selQuery").val();
        var editorQueryVal = editorQuery.getSession().getValue();
        content =editorQueryVal;
    }else if(nodeTreeType == "script"){
        connectionid = $("#selScript").val();
        var editorScriptVal = editorScript.getSession().getValue();
        content =editorScriptVal;
    }

    $.ajax({
        async : false,
        type: "post",
        url: "/EtlXml/SaveNodeInfoAjax",
        data: {
            nodeTreeType: nodeTreeType,
            content: content,
            connectionid:connectionid,
            nodeid: nodeid
        },
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data == 1) {
                //alert("调用成功");
                if(nodeTreeType == "connection"){
                    //修改当前connection节点名称为所选连接
                    //alert($("#" + nodeid).html());
                }

                return;
            }
            else
            {
                alert("添加节点失败!");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });

}

//单击节点时，加载相应节点信息（只加载proprety、conn、query、script）
function GetNodeInfoAjax() {
    var mytreetype = $("#hidTreeType").val();

    if(mytreetype == "properties" ||mytreetype == "connection" ||mytreetype == "query" ||mytreetype == "script" )
    {
        //var VarName = $("#txtval").val();
        var nodeid = $("#hidID").val();

        $.ajax({
            async : false,
            type: "get",
            url: "/EtlXml/GetNodeInfoAjax?ajaxparam="+nodeid,
            beforeSend: function (XMLHttpRequest) {
                //ShowLoading();
            },
            success: function (data) {
                if (data == 1) {
                    //alert("调用成功");
                    return;
                }
                else
                {
                    alert("添加节点失败!");
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                //HideLoading();
            },
            error: function () {
                //请求出错处理
            }
        });
    }
}

//添加节点
function AddNodeAjax(ajaxparam) {
    //执行异步调用
    $.ajax({
        async : false,
        type: "get",
        url: "/EtlXml/AddNodeAjax?ajaxparam="+ajaxparam,
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data == 1) {
                //alert("调用成功");
                return;
            }
            else
            {
                alert("添加节点失败!");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });
}

//加载树节点
function GetTreeNodesAllAjax()
{
    $.ajax({
        async : false,
        type: "get",
        url: "/EtlXml/GetTreeNodesAllAjax",
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data != 0) {
                var dataval = eval('(' + data+ ')')
                zNodes = dataval;
                //alert(dataval);
            }
            else
            {
                alert("添加节点失败!");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });
}

//根据树ID，返回节点信息
function GetTreeNodeInfoByIDAjax(nodeid)
{
    $.ajax({
        async : false,
        type: "get",
        url: "/EtlXml/GetTreeNodeInfoByIDAjax?nodeid="+nodeid,
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data != 0) {
                var dataval = eval('(' + data+ ')')
                return dataval;
            }
            else
            {
                alert("加载节点信息失败!");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });
}

//初始化时更新节点Number
function UpdateNodeNumber() {
    //如果zNodes中只有根节点，那么不用再初始化
    if(zNodes.length > 1) {
        for(var n = 0; n < zNodes.length; n++)
        {
            if(zNodes[n].mytreetype == "layer"){
                ++newLayerCount;
            }else if(zNodes[n].mytreetype == "createjob") {
                ++newCreateJobCount;
            }
            else if(zNodes[n].mytreetype == "updatejob") {
                ++newUpdateJobCount;
            }
            else if(zNodes[n].mytreetype == "properties") {
                ++newValCount;
            }
            else if(zNodes[n].mytreetype == "connection") {
                ++newConnectionCount;
            }if(zNodes[n].mytreetype == "query") {
            ++newQueryCount;
        }
            if(zNodes[n].mytreetype == "script") {
                ++newScriptCount;
            }
        }
    }
}

//加载数据源
function GetSelDatabasesAjax(){

    $("#selConn").empty();
    $("#selQuery").empty();
    $("#selScript").empty();

    $.ajax({
        async : false,
        type: "get",
        url: "/EtlXml/GetSelDatabasesAjax",
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data != 0) {
                dataBaseSelNodes= eval('(' + data+ ')');
                for(var selindex = 0; selindex < dataBaseSelNodes.length; selindex++)
                {
                    var optionSel = "<option value='"+dataBaseSelNodes[selindex].name+"'>"+dataBaseSelNodes[selindex].name+"</option>";
                    $("#selConn").append(optionSel);
                    $("#selQuery").append(optionSel);
                    $("#selScript").append(optionSel);
                }
            }
            else
            {
                alert("加载数据库信息失败!");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });
}

//生成EtlXML
function GetJobEtlXml(nodeid) {
    $.ajax({
        async : false,
        type: "get",
        url: "/EtlXml/GetJobEtlXml?nodeid="+nodeid,
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success: function (data) {
            if (data != null && data != "") {
                editor.getSession().setValue(data);
            }
            else
            {
                alert("ETLXML生成异常！");
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
        },
        error: function () {
            //请求出错处理
        }
    });
}

var xmlvar;
var xmlToTreeNodes;
var pIdAndIdList = "";
var hidjobid = $("#hidJobID").val();

//根据xml内容生成树结构，并保存xml内容
function createXmlToTree(obj,pid,pname,nodeid,typeStep,NoNodePidData) {
    //生成节点ID
    var connectionid = "";

    if(obj.nodeName.trim().toLowerCase() == "connection")
    {
        if (obj.attributes.getNamedItem("id") != null) {
            connectionid = obj.attributes.getNamedItem("id").textContent;
        }
        //else {
        //throw "错误：节点" + obj.context.nodeName + "的ID不能空！";
        // }
    }
    else
    {
        if (obj.attributes.getNamedItem("connection-id") != null) {
            connectionid = obj.attributes.getNamedItem("connection-id").textContent;
        }
        //else {
        //  throw "错误：节点" + obj.context.nodeName + "的connection-id不能空！";
        //}
    }

    var XmlIDIsName = "";
    if (obj.attributes.getNamedItem("id") != null && obj.attributes.getNamedItem("id").textContent.trim() != "") {
        XmlIDIsName = obj.attributes.getNamedItem("id").textContent;
    }
    else{
        XmlIDIsName = pname+"_"+(obj.nodeName.trim().toLowerCase() == "scripttemp" ? "script" : obj.nodeName.trim().toLowerCase())+typeStep;
    }

    var nodecontent = "";
    var nodename = "";
    var nowNoNodeData ="";
    var IsHaveChild = false;

    //获取节点内容
    if(obj.nodeName.trim().toLowerCase() == "properties" || obj.nodeName.trim().toLowerCase() == "connection"){
        nodecontent = obj.innerHTML;
    }
    else if (obj.childNodes != null && obj.childNodes.length > 0) {
        for(var i = 0; i < obj.childNodes.length; i++){
            var fortempNodeName = obj.childNodes[i].nodeName.trim().toLowerCase();
            if(fortempNodeName=="#text"){
                nodecontent += obj.childNodes[i].textContent;
                continue;
            }else if(fortempNodeName=="#comment"){
                nodecontent += "<!--"+ obj.childNodes[i].textContent +"-->";
                continue;
            }else if(fortempNodeName == "connection" ||fortempNodeName == "query"||fortempNodeName == "scripttemp" ){
                IsHaveChild = true;
                break;
            }
            //nodecontent = nodecontent +obj.context.childNodes[i].textContent;
        }
        //nodecontent = obj.contents()[0].textContent.trim();
    }

    if(IsHaveChild){
        nodecontent="";
    }else{
        if(obj.nodeName.trim().toLowerCase() == "properties"){
            nodecontent  = encodeURIComponent(nodecontent);
        }else{
            nodecontent  = encodeURIComponent(nodecontent.trimRight());
        }

    }

    xmlToTreeNodes += "{\"pId\":\""+pid+"\",\"id\":\""+nodeid+"\",\"mytreetype\":\""+(obj.nodeName.trim().toLowerCase() == "scripttemp" ? "script" : obj.nodeName.trim().toLowerCase())+"\",\"nodecontent\":\"" + nodecontent + "\",\"name\":\"" + XmlIDIsName+ "\",\"connectionid\":\""+connectionid+"\",\"jobid\":\""+$("#hidJobID").val()+"\",\"comment\":\""+encodeURIComponent(NoNodePidData)+"\" },";

    if (IsHaveChild) {
        //如果有, 遍历之
        var nodeIdStep = 0;
        var preStep = 0;
        var connStep = 0;
        var queryStep = 0;
        var scriptStep = 0;
        var typeStep = 0;

        var NowNoNodeData = "";
        for(var topi = 0; topi < obj.childNodes.length; topi++ ){
            try {
                var nowChildNodeName = obj.childNodes[topi].nodeName.trim().toLowerCase();
                //判断是否为节点
                //nowChildNodeName = $(this).context.nodeName.trim().toLowerCase();
                if(nowChildNodeName=="#text"){
                    NowNoNodeData += obj.childNodes[topi].textContent;
                    continue;
                }else if(nowChildNodeName=="#comment"){
                    NowNoNodeData +="<!--"+ obj.childNodes[topi].textContent+"-->";
                    continue;
                }else if(nowChildNodeName=="properties"){
                    nodeIdStep++;
                    typeStep = ++preStep;
                }else if(nowChildNodeName=="connection"){
                    nodeIdStep++;
                    typeStep = ++connStep;
                }else if(nowChildNodeName=="query"){
                    nodeIdStep++;
                    typeStep = ++queryStep;
                }else if(nowChildNodeName=="scripttemp"){
                    nodeIdStep++;
                    typeStep = ++scriptStep;
                }
                createXmlToTree(obj.childNodes[topi],nodeid,XmlIDIsName,(Number(nodeid) * 10 + nodeIdStep),typeStep,NowNoNodeData);
                NowNoNodeData ="";
            }
            catch (e) {
                alert(e);
                return false;
            }
        }
    } else {
        //如果没有子DOM, 返回false
        return false;
    }

}


function btnSaveXML_click() {
    xmlvar = "";
    xmlToTreeNodes = "";
    xmlvar = editor.getSession().getValue();

    xmlvar = xmlvar.replace(/\<script/gi, "<scripttemp");
    xmlvar = xmlvar.replace(/<\/script/gi, "</scripttemp");

    if(xmlvar.trim() != ""){
        var nodeIdStep = 0;
        var preStep = 0;
        var connStep = 0;
        var queryStep = 0;
        var scriptStep = 0;
        var typeStep = 0;
        //查询出第一层注释

        var NoNodeData = "";
        for(var topi = 0; topi < $(xmlvar)[1].childNodes.length; topi++ ){
            try {
                var nowChildNodeName = $(xmlvar)[1].childNodes[topi].nodeName.trim().toLowerCase();
                //判断是否为节点
                //nowChildNodeName = $(this).context.nodeName.trim().toLowerCase();
                if(nowChildNodeName=="#text"){
                    NoNodeData += $(xmlvar)[1].childNodes[topi].textContent;
                    continue;
                }else if(nowChildNodeName=="#comment"){
                    NoNodeData += "<!--"+$(xmlvar)[1].childNodes[topi].textContent+"-->";
                    continue;
                }else if(nowChildNodeName=="properties"){
                    nodeIdStep++;
                    typeStep = ++preStep;
                }else if(nowChildNodeName=="connection"){
                    nodeIdStep++;
                    typeStep = ++connStep;
                }else if(nowChildNodeName=="query"){
                    nodeIdStep++;
                    typeStep = ++queryStep;
                }else if(nowChildNodeName=="scripttemp"){
                    nodeIdStep++;
                    typeStep = ++scriptStep;
                }
                createXmlToTree($(xmlvar)[1].childNodes[topi],$("#hidJobID").val(),$("#hidJobName").val(),(Number($("#hidJobID").val()) * 10 + nodeIdStep),typeStep,NoNodeData);
                NoNodeData = "";
            }
            catch (e) {
                alert(e);
                return false;
            }

        }
    }

    if(xmlToTreeNodes != ""){
        xmlToTreeNodes ="[" + xmlToTreeNodes.substr(0,xmlToTreeNodes.length - 1)+"]";
        var jobid = $("#hidJobID").val();
        $.ajax({
            async : false,
            type: "post",
            url: "/EtlXml/SaveXMLAjax",
            data:{nodeids:xmlToTreeNodes,jobid:$("#hidJobID").val()},
            beforeSend: function (XMLHttpRequest) {
                //ShowLoading();
            },
            success: function (data) {

            },
            complete: function (XMLHttpRequest, textStatus) {
                //HideLoading();
            },
            error: function () {
                //请求出错处理
            }
        });
    }
}

//将新增的节点移动到同类型节点后
function TreeMoveNode(movepid,moveid){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var nownode =zTree.getNodeByParam("id", moveid, null);
    var nowpidnode = zTree.getNodeByParam("id", movepid, null);
    var targetnode;
    var prepritynode;
    //查询父节点下同类型最后一个
    if(nownode.mytreetype != "layer" && nownode.mytreetype != "query" && nownode.mytreetype != "script"){
        if(nowpidnode != null &&   nowpidnode.children != null  && nowpidnode.children.length> 0){
            for(var movei = 0; movei < nowpidnode.children.length; movei++){
                if( nowpidnode.children[movei].id != nownode.id){
                    if(nowpidnode.children[movei].mytreetype == nownode.mytreetype){
                        targetnode = nowpidnode.children[movei];
                    }
                    if(nowpidnode.children[movei].mytreetype == "properties"){
                        prepritynode = nowpidnode.children[movei];
                    }
                }
            }
        }

        //移动
        if(targetnode != null){
            zTree.moveNode(targetnode, nownode, "next");
        }else if(nownode.mytreetype == "properties" ){
            //添加到任务节点下的第一个节点
            if(nowpidnode != null && nowpidnode.children.length> 0){
                zTree.moveNode(nowpidnode.children[0], nownode, "prev");
            }
        }else if(nownode.mytreetype == "connection" ){
            //如果有preprity则添加到其后，否则添加到任务节点下
            if(nowpidnode != null && nowpidnode.children.length> 0){
                if(prepritynode != null){
                    zTree.moveNode(prepritynode, nownode, "next");
                }
                else{
                    zTree.moveNode(nowpidnode.children[0], nownode, "prev");
                }
            }
        }
    }

}

//根据爹节点ID，查询当前爹节点下，有多少个childNodeType类型节点，返回个数
function GetPidNodeTypeNum(movepid,childNodeType){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var nowpidnode = zTree.getNodeByParam("id", movepid, null);
    var returnNum = 0;
    if(nowpidnode != null &&  nowpidnode.children != null && nowpidnode.children.length> 0){
        for(var movei = 0; movei < nowpidnode.children.length; movei++){
            if( nowpidnode.children[movei].mytreetype == childNodeType){
                returnNum++;
            }
        }
    }
    return returnNum;
}



//********************************自定义函数结束********************************************//


$(document).ready(function () {

    //加载树节点
    GetTreeNodesAllAjax();

    $.fn.zTree.init($("#treeDemo"), setting, zNodes);

    //UpdateNodeNumber();
    //$("#addParent").bind("click", {isParent:true}, add);
    //$("#seleAddNode").change(myTreeSelectChange);

    $("#seleAddNode").bind("change", { isParent: true }, add);

    $("#edit").bind("click", edit);
    $("#remove").bind("click", remove);
    $("#clearChildren").bind("click", clearChildren);

    $("#btnValSave").bind("click", SaveNodeInfoAjax);
});
